<template>
  <div class="p-2">
    <!-- OTA历史记录模块 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="设备ID" prop="deviceId">
          <el-input
            v-model="queryParams.deviceId"
            placeholder="请输入设备ID"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="版本号" prop="versionNumber">
          <el-input
            v-model="queryParams.versionNumber"
            placeholder="请输入版本号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="升级状态" prop="upgradeStatus">
          <el-select v-model="queryParams.upgradeStatus" placeholder="请选择升级状态" clearable style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="升级中" value="upgrading" />
            <el-option label="升级成功" value="success" />
            <el-option label="升级失败" value="failed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="等待中" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="传感器" value="sensor" />
            <el-option label="控制器" value="controller" />
            <el-option label="网关" value="gateway" />
            <el-option label="摄像头" value="camera" />
          </el-select>
        </el-form-item>
        <el-form-item label="升级时间" prop="upgradeTime">
          <el-date-picker
            v-model="queryParams.upgradeTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="10" style="margin-bottom: 8px">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statistics.total }}</div>
            <div class="stat-label">总升级次数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value success">{{ statistics.success }}</div>
            <div class="stat-label">成功次数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value failed">{{ statistics.failed }}</div>
            <div class="stat-label">失败次数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value rate">{{ statistics.successRate }}%</div>
            <div class="stat-label">成功率</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="primary" icon="Download" @click="handleExport">导出记录</el-button>
          <el-button type="warning" icon="Delete" @click="handleBatchDelete" :disabled="!selectedIds.length">批量删除</el-button>
          <el-button type="info" icon="Refresh" @click="handleRefresh">刷新</el-button>
        </div>
        <div class="toolbar-right">
          <el-tooltip content="密度">
            <el-dropdown trigger="click" @command="handleTableSizeChange">
              <el-button circle>
                <el-icon><Operation /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="large">宽松</el-dropdown-item>
                  <el-dropdown-item command="default">默认</el-dropdown-item>
                  <el-dropdown-item command="small">紧凑</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-tooltip>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
        v-loading="loading"
        :data="recordList"
        :size="tableSize"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="升级ID" prop="upgradeId" width="120" align="center" />
        <el-table-column label="设备信息" width="200">
          <template #default="scope">
            <div class="device-info">
              <div class="device-id">{{ scope.row.deviceId }}</div>
              <div class="device-name">{{ scope.row.deviceName }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="设备类型" prop="deviceType" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getDeviceTypeTagType(scope.row.deviceType)" size="small">
              {{ getDeviceTypeText(scope.row.deviceType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="版本信息" width="180">
          <template #default="scope">
            <div class="version-info">
              <div class="version-from">{{ scope.row.fromVersion }} →</div>
              <div class="version-to">{{ scope.row.toVersion }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="升级状态" prop="upgradeStatus" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.upgradeStatus)" size="small">
              {{ getStatusText(scope.row.upgradeStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="升级进度" prop="progress" width="150" align="center">
          <template #default="scope">
            <el-progress
              :percentage="scope.row.progress"
              :status="getProgressStatus(scope.row.upgradeStatus)"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column label="升级方式" prop="upgradeType" width="100" align="center">
          <template #default="scope">
            <el-tag size="small" plain>
              {{ getUpgradeTypeText(scope.row.upgradeType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" prop="startTime" width="160" align="center" />
        <el-table-column label="结束时间" prop="endTime" width="160" align="center" />
        <el-table-column label="耗时" prop="duration" width="100" align="center">
          <template #default="scope">
            <span v-if="scope.row.duration">{{ scope.row.duration }}s</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="失败原因" prop="failureReason" width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="240" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-button type="info" size="small" @click="handleViewLog(scope.row)">日志</el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleRetry(scope.row)"
              v-if="scope.row.upgradeStatus === 'failed'"
            >
              重试
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :small="false"
          :disabled="loading"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 升级详情对话框 -->
    <el-dialog title="升级详情" v-model="detailDialog.visible" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="升级ID">{{ detailData.upgradeId }}</el-descriptions-item>
        <el-descriptions-item label="设备ID">{{ detailData.deviceId }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ detailData.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="设备类型">{{ getDeviceTypeText(detailData.deviceType) }}</el-descriptions-item>
        <el-descriptions-item label="原版本">{{ detailData.fromVersion }}</el-descriptions-item>
        <el-descriptions-item label="目标版本">{{ detailData.toVersion }}</el-descriptions-item>
        <el-descriptions-item label="升级状态">{{ getStatusText(detailData.upgradeStatus) }}</el-descriptions-item>
        <el-descriptions-item label="升级进度">{{ detailData.progress }}%</el-descriptions-item>
        <el-descriptions-item label="升级方式">{{ getUpgradeTypeText(detailData.upgradeType) }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ detailData.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ detailData.endTime }}</el-descriptions-item>
        <el-descriptions-item label="升级耗时">{{ detailData.duration }}s</el-descriptions-item>
        <el-descriptions-item label="文件大小">{{ detailData.fileSize }}</el-descriptions-item>
        <el-descriptions-item label="下载速度">{{ detailData.downloadSpeed }}</el-descriptions-item>
        <el-descriptions-item label="失败原因" :span="2" v-if="detailData.upgradeStatus === 'failed'">
          {{ detailData.failureReason }}
        </el-descriptions-item>
        <el-descriptions-item label="升级说明" :span="2">
          {{ detailData.description }}
        </el-descriptions-item>
      </el-descriptions>
      
      <!-- 升级步骤 -->
      <div class="upgrade-steps">
        <h4>升级步骤</h4>
        <el-steps direction="vertical" :active="detailData.currentStep">
          <el-step title="准备阶段" description="检查设备状态和网络连接" />
          <el-step title="下载固件" description="从服务器下载固件文件" />
          <el-step title="验证固件" description="校验固件完整性和签名" />
          <el-step title="安装固件" description="将固件写入设备" />
          <el-step title="重启设备" description="重启设备并验证版本" />
          <el-step title="完成升级" description="升级完成，设备正常运行" />
        </el-steps>
      </div>
    </el-dialog>

    <!-- 升级日志对话框 -->
    <el-dialog title="升级日志" v-model="logDialog.visible" width="900px" append-to-body>
      <div class="log-container">
        <div class="log-header">
          <el-button type="primary" size="small" @click="handleRefreshLog">刷新日志</el-button>
          <el-button type="info" size="small" @click="handleDownloadLog">下载日志</el-button>
          <el-switch v-model="autoRefresh" active-text="自动刷新" />
        </div>
        <div class="log-content">
          <pre>{{ logContent }}</pre>
        </div>
      </div>
    </el-dialog>

    <!-- 重试升级对话框 -->
    <el-dialog title="重试升级" v-model="retryDialog.visible" width="500px" append-to-body>
      <el-form :model="retryForm" label-width="100px">
        <el-form-item label="设备ID">
          <el-input v-model="retryForm.deviceId" readonly />
        </el-form-item>
        <el-form-item label="目标版本">
          <el-input v-model="retryForm.targetVersion" readonly />
        </el-form-item>
        <el-form-item label="重试原因">
          <el-input v-model="retryForm.retryReason" type="textarea" :rows="3" placeholder="请输入重试原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="retryDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmRetry">确认重试</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="HistoryRecord" lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, Delete, Operation } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const tableSize = ref('default')
const selectedIds = ref([])
const total = ref(0)
const autoRefresh = ref(false)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  deviceId: '',
  versionNumber: '',
  upgradeStatus: '',
  deviceType: '',
  upgradeTime: null
})

// 统计数据
const statistics = reactive({
  total: 1256,
  success: 1089,
  failed: 167,
  successRate: 86.7
})

// 升级记录列表
const recordList = ref([
  {
    upgradeId: 'UPG001',
    deviceId: 'DEV001',
    deviceName: '温度传感器01',
    deviceType: 'sensor',
    fromVersion: 'v1.0.0',
    toVersion: 'v1.1.0',
    upgradeStatus: 'success',
    progress: 100,
    upgradeType: 'auto',
    startTime: '2024-01-15 10:30:00',
    endTime: '2024-01-15 10:35:20',
    duration: 320,
    failureReason: '',
    fileSize: '2.5MB',
    downloadSpeed: '128KB/s',
    description: '修复温度读取异常问题'
  },
  {
    upgradeId: 'UPG002',
    deviceId: 'DEV002',
    deviceName: '控制器设备01',
    deviceType: 'controller',
    fromVersion: 'v2.0.0',
    toVersion: 'v2.1.0',
    upgradeStatus: 'failed',
    progress: 45,
    upgradeType: 'manual',
    startTime: '2024-01-15 11:00:00',
    endTime: '2024-01-15 11:05:30',
    duration: 330,
    failureReason: '网络连接超时',
    fileSize: '5.2MB',
    downloadSpeed: '64KB/s',
    description: '增加新的控制算法'
  },
  {
    upgradeId: 'UPG003',
    deviceId: 'DEV003',
    deviceName: '网关设备01',
    deviceType: 'gateway',
    fromVersion: 'v1.5.0',
    toVersion: 'v1.6.0',
    upgradeStatus: 'upgrading',
    progress: 75,
    upgradeType: 'scheduled',
    startTime: '2024-01-15 12:00:00',
    endTime: '',
    duration: null,
    failureReason: '',
    fileSize: '8.1MB',
    downloadSpeed: '256KB/s',
    description: '优化数据传输性能'
  },
  {
    upgradeId: 'UPG004',
    deviceId: 'DEV004',
    deviceName: '摄像头设备01',
    deviceType: 'camera',
    fromVersion: 'v3.0.0',
    toVersion: 'v3.1.0',
    upgradeStatus: 'pending',
    progress: 0,
    upgradeType: 'manual',
    startTime: '',
    endTime: '',
    duration: null,
    failureReason: '',
    fileSize: '12.3MB',
    downloadSpeed: '',
    description: '增强图像处理能力'
  },
  {
    upgradeId: 'UPG005',
    deviceId: 'DEV005',
    deviceName: '温度传感器02',
    deviceType: 'sensor',
    fromVersion: 'v1.0.0',
    toVersion: 'v1.1.0',
    upgradeStatus: 'cancelled',
    progress: 25,
    upgradeType: 'auto',
    startTime: '2024-01-15 09:30:00',
    endTime: '2024-01-15 09:32:15',
    duration: 135,
    failureReason: '用户取消',
    fileSize: '2.5MB',
    downloadSpeed: '96KB/s',
    description: '修复温度读取异常问题'
  }
])

// 对话框数据
const detailDialog = reactive({
  visible: false
})

const logDialog = reactive({
  visible: false
})

const retryDialog = reactive({
  visible: false
})

const detailData = reactive({})
const logContent = ref('')
const retryForm = reactive({
  deviceId: '',
  targetVersion: '',
  retryReason: ''
})

// 获取设备类型文本
const getDeviceTypeText = (type: string) => {
  const typeMap = {
    sensor: '传感器',
    controller: '控制器',
    gateway: '网关',
    camera: '摄像头'
  }
  return typeMap[type] || type
}

// 获取设备类型标签类型
const getDeviceTypeTagType = (type: string) => {
  const typeMap = {
    sensor: 'success',
    controller: 'warning',
    gateway: 'info',
    camera: 'danger'
  }
  return typeMap[type] || ''
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    upgrading: '升级中',
    success: '升级成功',
    failed: '升级失败',
    cancelled: '已取消',
    pending: '等待中'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap = {
    upgrading: 'warning',
    success: 'success',
    failed: 'danger',
    cancelled: 'info',
    pending: 'info'
  }
  return statusMap[status] || ''
}

// 获取进度状态
const getProgressStatus = (status: string) => {
  const statusMap = {
    upgrading: undefined,
    success: 'success',
    failed: 'exception',
    cancelled: 'warning',
    pending: undefined
  }
  return statusMap[status]
}

// 获取升级方式文本
const getUpgradeTypeText = (type: string) => {
  const typeMap = {
    auto: '自动',
    manual: '手动',
    scheduled: '定时'
  }
  return typeMap[type] || type
}

// 查询
const handleQuery = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    loading.value = false
    ElMessage.success('查询完成')
  }, 1000)
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 20,
    deviceId: '',
    versionNumber: '',
    upgradeStatus: '',
    deviceType: '',
    upgradeTime: null
  })
  handleQuery()
}

// 导出记录
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}条记录？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    selectedIds.value = []
  })
}

// 刷新
const handleRefresh = () => {
  handleQuery()
}

// 表格大小变化
const handleTableSizeChange = (size: string) => {
  tableSize.value = size
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.upgradeId)
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  handleQuery()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page
  handleQuery()
}

// 查看详情
const handleViewDetail = (row: any) => {
  Object.assign(detailData, {
    ...row,
    currentStep: row.upgradeStatus === 'success' ? 6 : 
                 row.upgradeStatus === 'failed' ? 3 : 
                 row.upgradeStatus === 'upgrading' ? 4 : 1
  })
  detailDialog.visible = true
}

// 查看日志
const handleViewLog = (row: any) => {
  logContent.value = `[2024-01-15 10:30:00] 开始升级设备 ${row.deviceId}\n[2024-01-15 10:30:05] 检查设备状态...\n[2024-01-15 10:30:10] 设备状态正常，开始下载固件\n[2024-01-15 10:30:15] 固件下载中... 10%\n[2024-01-15 10:31:00] 固件下载中... 50%\n[2024-01-15 10:31:30] 固件下载完成\n[2024-01-15 10:31:35] 开始验证固件...\n[2024-01-15 10:31:40] 固件验证通过\n[2024-01-15 10:31:45] 开始安装固件...\n[2024-01-15 10:33:00] 固件安装中... 25%\n[2024-01-15 10:34:00] 固件安装中... 75%\n[2024-01-15 10:34:30] 固件安装完成\n[2024-01-15 10:34:35] 重启设备...\n[2024-01-15 10:35:00] 设备重启完成\n[2024-01-15 10:35:10] 验证新版本...\n[2024-01-15 10:35:20] 升级完成，版本: ${row.toVersion}`
  logDialog.visible = true
}

// 重试升级
const handleRetry = (row: any) => {
  Object.assign(retryForm, {
    deviceId: row.deviceId,
    targetVersion: row.toVersion,
    retryReason: ''
  })
  retryDialog.visible = true
}

// 确认重试
const handleConfirmRetry = () => {
  ElMessage.success('重试升级已启动')
  retryDialog.visible = false
}

// 删除记录
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除升级记录 ${row.upgradeId}？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

// 刷新日志
const handleRefreshLog = () => {
  ElMessage.success('日志已刷新')
}

// 下载日志
const handleDownloadLog = () => {
  ElMessage.success('日志下载成功')
}

// 组件挂载
onMounted(() => {
  handleQuery()
  total.value = recordList.value.length
})
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  gap: 10px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.failed {
  color: #f56c6c;
}

.stat-value.rate {
  color: #409eff;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.device-info {
  text-align: left;
}

.device-id {
  font-weight: bold;
  color: #303133;
}

.device-name {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.version-info {
  text-align: left;
}

.version-from {
  color: #909399;
  font-size: 12px;
}

.version-to {
  color: #303133;
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.upgrade-steps {
  margin-top: 20px;
}

.upgrade-steps h4 {
  margin-bottom: 15px;
  color: #303133;
}

.log-container {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.log-content {
  flex: 1;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  overflow-y: auto;
}

.log-content pre {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #303133;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.dialog-footer {
  text-align: right;
}
</style>